import axios from 'axios'

const signer = require("./signer") 
const domain = process.env.VUE_APP_DOMAIN
const appKey = process.env.VUE_APP_KEY
const appSecret = process.env.VUE_APP_SECRET
const sig = new signer.Signer()
sig.Key = appKey
sig.Secret = appSecret

const instance = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    timeout: 1000 * 100,
    withCredentials: false,
  });

  // 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    console.log(response)
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    
    return Promise.reject(error);
  });

 export function get(suffix: string, params?: object) {
  if (params != undefined && params != null){
    suffix = suffix + "?"
    Object.keys(params).forEach(name => {
      console.log(params[name as keyof object]);
      suffix = suffix + `${name}=${params[name as keyof object]}`
    })
  }

  var r = new signer.HttpRequest("GET", `${domain}${suffix}`);
  r.headers["x-stage"] = "RELEASE"
  var opts = sig.Sign(r)
  const response = instance.get(suffix, {
    headers: opts.headers
  })
  return response
}

export function post(suffix: string, data?: object, params?: object) {
  if (params != undefined && params != null){
    suffix = suffix + "?"
    Object.keys(params).forEach(name => {
      console.log(params[name as keyof object]);
      suffix = suffix + `${name}=${params[name as keyof object]}`
    })
  }
  var r = new signer.HttpRequest("POST", `${domain}${suffix}`);
  r.body = JSON.stringify(data)
  r.headers["x-stage"] = "RELEASE"
  var opts = sig.Sign(r)
  const response = instance.post(suffix, r.body,{
    headers: opts.headers
  })
  return response
}

export function option(suffix: string) {
  var r = new signer.HttpRequest("OPTIONS", `${domain}${suffix}`);
//   r.body = JSON.stringify(data)
  r.headers["x-stage"] = "RELEASE"
  r.headers["Access-Control-Request-Method"]= "POST,OPTIONS"
  r.headers["Access-Control-Request-Headers"]= "x-sdk-date"
//   var opts = sig.Sign(r)
  const response = instance.options(suffix,{
    headers: r.headers
  })
  return response
}